#include <chrono>
#include "../logs/log.h"

void bench(const std::string& logger_name, size_t thr_count, size_t msg_count, size_t msg_len)
{
    // 获取日志器
    Logger::ptr logger = getLogger(logger_name);
    if (logger.get() == nullptr)
    {
        return;
    }

    std::cout << "测试日志：" << msg_count << "条，总大小：" << (msg_count * msg_len) / 1024 << "KB\n";
    // 组织指定长度的日志消息
    std::string msg(msg_len - 1, 'A'); // 少一个字节，为了给，末尾添加换行
    // 创建指定数量的线程
    std::vector<std::thread> threads;
    std::vector<double> cost_ary(thr_count);
    size_t msg_per_thr = msg_count / thr_count; // 总日志数量/线程数量，每个线程输出日志数量
    for (int i = 0; i < thr_count; i++)
    {
        threads.emplace_back([&, i]()
                             {
            // 线程函数内部开始计时
            auto start = std::chrono::high_resolution_clock::now();
            // 循环写日志
            for (int j = 0; j < msg_per_thr; j++)
            {
                logger->fatal("%s", msg.c_str());
            }
            // 线程函数内部结束计时
            auto end = std::chrono::high_resolution_clock::now();
            std::chrono::duration<double> cost = end - start;
            cost_ary[i] = cost.count();
            std::cout << "线程" << i << "\t输出数量:" << msg_per_thr << ", 耗时:" << cost.count() << "s" << std::endl; });
    }

    for (int i = 0; i < thr_count; i++)
    {
        threads[i].join();
    }

    // 计算总耗时，多线程并发处理的，所以耗时最多的就是总时间
    double max_cost = cost_ary[0];
    for (int i = 0; i < thr_count; i++)
    {
        max_cost = max_cost < cost_ary[i] ? cost_ary[i] : max_cost;
    }

    size_t msg_per_sec = msg_count / max_cost;
    size_t size_per_sec = (msg_count * msg_len) / (max_cost * 1024);
    // 输出打印
    std::cout << "总耗时：" << max_cost << "条\n";
    std::cout << "每秒输出日志数量：" << msg_per_sec << "条\n";
    std::cout << "每秒输出日志大小：" << size_per_sec << "KB\n";
}

void sync_bench()
{
    std::unique_ptr<LoggerBuilder> builder(new GlobalLoggerBuilder());
    builder->buildLoggerName("sync-logger");
    builder->buildFormatter("%m%n");
    builder->buildLoggerType(LoggerType::LOGGER_SYNC);
    builder->buildSink<FileSink>("./logfile/sync.log"); 
    builder->build();
    bench("sync-logger", 3, 1000000, 100);
}

void async_bench()
{
    std::unique_ptr<LoggerBuilder> builder(new GlobalLoggerBuilder());
    builder->buildLoggerName("async-logger");
    builder->buildFormatter("%m%n");
    builder->buildLoggerType(LoggerType::LOGGER_ASYNC);
    builder->buildEnabelUnSafAsynce();  // 非安全模式，为了将落地时间排出
    builder->buildSink<FileSink>("./logfile/sync.log");
    builder->build();
    bench("async-logger", 5, 1000000, 100);
}

int main()
{
    async_bench();
    return 0;
}